//
//  ThroadToServer.m
//  PiPiPineapple
//
//  Created by 李晓东 on 17/10/28.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

#import "ThroadToServer.h"


@interface ThroadToServer()
@property (nonatomic, strong) NSString *appcode;
@property (nonatomic, strong) NSString *host;
@property (nonatomic, strong) NSString *path;
@property (nonatomic, strong) NSString *method;
@property (nonatomic, strong) NSString *querys;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) NSString *bodys;

@property (nonatomic, strong) ResultOfDoubleChromosphere resultOfDoubleChromosphere;

@end

@implementation ThroadToServer

+ (instancetype)shareThroadToServer{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ThroadToServer alloc]init];
    });
    return instance;
}

- (instancetype)initWithParams:(ResultOfDoubleChromosphere)resultOfDoubleChromosphere{
    _appcode = @"5ca6cbf36a9d45a78a2fc4b071f2333e";
    _host = @"http://jisucpkj.market.alicloudapi.com";
    _method = @"GET";
    
    _bodys = @"";
    self.resultOfDoubleChromosphere = resultOfDoubleChromosphere;
    return self;
}

- (NSArray *)loadDoubleChromosphereOfType:(NSString *)method withIssueno:(NSString *)issueno ofNumber:(NSInteger)number{
    _path = [NSString stringWithFormat:@"/caipiao/%@", method];
    _querys = [NSString stringWithFormat:@"?caipiaoid=11&issueno=%@%@", issueno == nil ? @"" : issueno, number == 0 ? nil : [NSString stringWithFormat:@"&num=%ld", number]];
    _url = [NSString stringWithFormat:@"%@%@%@",  _host,  _path , _querys];
    
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{
        [self accessServer];
    });
    return nil;
}

- (void)loadDoubleChromosphereByIssueno:(NSString *)issueno{
    _path = @"/caipiao/query";
    _querys = [NSString stringWithFormat:@"?caipiaoid=11&issueno=%@", issueno == nil ? @"" : issueno];
    _url = [NSString stringWithFormat:@"%@%@%@",  _host,  _path , _querys];
    
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{
        [self accessServer];
    });
    
}

- (NSArray *)loadDoubleChromospheresByIssueno:(NSString *)issueno andRows:(NSInteger)row{
    if (row == 0) {
        self.resultOfDoubleChromosphere(nil);
        return nil;
    }
    _path = @"/caipiao/history";
    _querys = [NSString stringWithFormat:@"?caipiaoid=11&issueno=%@&num=%ld", issueno == nil ? @"" : issueno, row];
    _url = [NSString stringWithFormat:@"%@%@%@",  _host,  _path , _querys];
    
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{
        [self accessServer];
    });
    
    return nil;
}

- (void)accessServer{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: _url]  cachePolicy:1  timeoutInterval:  5];
    request.HTTPMethod  =  _method;
    [request addValue:  [NSString  stringWithFormat:@"APPCODE %@" ,  _appcode]  forHTTPHeaderField:  @"Authorization"]; 
    NSURLSession *requestSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSLog(@"threadOut%@", [NSThread currentThread]);
    NSURLSessionDataTask *task = [requestSession dataTaskWithRequest:request
    completionHandler:^(NSData * _Nullable body , NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"Response object: %@, %@" , response, error);
        
        id jsonObj = [NSJSONSerialization JSONObjectWithData:body options:NSJSONReadingAllowFragments error:nil];
        
        NSMutableArray *resultMutableArray = [NSMutableArray arrayWithCapacity:2];
        
        NSDictionary *dict = (NSDictionary *)jsonObj;
        
        [resultMutableArray addObjectsFromArray: [self changeIntoDoubleChromosphere:dict]];
        
        NSString *bodyString = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
        //打印应答中的body
        NSLog(@"Response body: %@" , bodyString);
        NSLog(@"threadInner%@", [NSThread currentThread]);
        self.resultOfDoubleChromosphere(resultMutableArray);
    }];
    
    [task resume];
}

- (NSArray *)changeIntoDoubleChromosphere:(id)obj{
    NSMutableArray *resultMutableArray = [NSMutableArray arrayWithCapacity:2];
    
    NSDictionary *dict = (NSDictionary *)obj;
    if (((NSDictionary *)dict[@"result"])[@"list"] != nil) {
        NSArray *array = ((NSDictionary *)dict[@"result"])[@"list"];
        for (id tempObj in array) {
            
            NSDictionary *tempDict = (NSDictionary *)tempObj;
            DoubleChromosphere *doubleChromosphere = [DoubleChromosphere doubleChromosphere:tempDict];
            [resultMutableArray addObject:doubleChromosphere];
        }
    } else if (((NSDictionary *)dict[@"result"])[@"list"] == nil) {
        NSDictionary *tempDict = ((NSDictionary *)dict[@"result"]);
        DoubleChromosphere *doubleChromosphere = [DoubleChromosphere doubleChromosphere:tempDict];
        [resultMutableArray addObject:doubleChromosphere];
    }

    return resultMutableArray;
}

@end

